package client;

import java.io.*;
import java.net.*;

import chat.ChatProtocol;
import client.ChatClient.ReadIn;

/**
 * This thread listens to the input stream to the server and updates
 * the background class ReadIn, which stores the last message the
 * server has received.
 * 
 * @author derykegan
 *
 */
public class ChatThreadListen extends Thread{
	
	InputStream in;
	ObjectInputStream ois;
	ReadIn r;
	private boolean active = true;
	
	/**
	 * Creates new thread for use by server.
	 * @param in InputStream to listen to
	 * @param r ReadIn background object to write to
	 */
	public ChatThreadListen(InputStream in, ReadIn r){
		this.in = in;
		this.r = r;
	}
	
	/**
	 * Execute server listening.
	 */
	public void run(){
		try {
			ois = new ObjectInputStream(in);
			
			while(active){
				ChatProtocol fromServer = (ChatProtocol) ois.readObject();
				r.addMessage(fromServer);
				Thread.sleep(50);
			}
			
		} 
		
		catch (Exception e){
			System.out.println("Error with listen thread: " + e);
		}
	}
	
	/**
	 * Cause thread to stop executing.
	 */
	protected void shutDown(){
		active = false;
	}

}
